package cvi.com.reader.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnDismissListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cvi.com.reader.R;
import cvi.com.reader.activity.AuditionActivity;
import cvi.com.reader.activity.PersonalActivity;
import cvi.com.reader.activity.PictureBookAuditionActivity;
import cvi.com.reader.adapter.PersonalAdapter;
import cvi.com.reader.base.BaseFragment;
import cvi.com.reader.bean.ChartDataBean;
import cvi.com.reader.bean.DeleteAllPubilcDataListener;
import cvi.com.reader.bean.PublicDisplayListnener;
import cvi.com.reader.bean.constant;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.refresh.CustomRefreshFooter;
import cvi.com.reader.tool.refresh.CustomRefreshHeader;
import cvi.com.reader.widgets.MultiStateView;
import cvi.com.reader.widgets.MyGridView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 梅涛 on 2020/7/30.
 * <p>
 * 个人中心-我的发布
 */

public class PersonalFragment extends BaseFragment implements PersonalAdapter.DeleteListener, DeleteAllPubilcDataListener {

    @BindView(R.id.gridview)
    MyGridView gridview;
    /* @BindView(R.id.delete_all)
     LinearLayout deleteAll;*/
    Unbinder unbinder;
    @BindView(R.id.no_data)
    TextView noData;
    @BindView(R.id.stateView)
    MultiStateView stateView;
    @BindView(R.id.smartRefreshLayout_home)
    SmartRefreshLayout smartRefreshLayout;
    private String type;
    private List<ChartDataBean.DataBean> dataBeanList = new ArrayList<>();
    private PersonalAdapter personalAdapter = null;
    public DialogPlus deleteDialog;
    private PublicDisplayListnener publicDisplayListnener;
    private MyReceiver myReceiver;

    public PublicDisplayListnener getPublicDisplayListnener() {
        return publicDisplayListnener;
    }

    public void setPublicDisplayListnener(PublicDisplayListnener publicDisplayListnener) {
        this.publicDisplayListnener = publicDisplayListnener;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        type = bundle.getString("type");
        unbinder = ButterKnife.bind(this, super.onCreateView(inflater, container, savedInstanceState));
        Log.d("PersonalCollectFragment", "type1111=" + type);
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(constant.MYPUBLIC_MYRECEIVER);
        getActivity().registerReceiver(myReceiver, intentFilter);
        initSmartRefreshLayout();
        return super.onCreateView(inflater, container, savedInstanceState);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragemt_personal;

    }

    @Override
    protected boolean isBindEventBus() {
        return false;
    }

    @Override
    protected void initData() {
        getMyPublicData();
    }

    //我的发布数据
    private void getMyPublicData() {
        dataBeanList.clear();
        NetWorkManager.getInstance().getNetWorkApiService().getPublicData(constant.MYPUBLIC).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        smartRefreshLayout.setEnableRefresh(true);
                        getData(response);
                        stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        smartRefreshLayout.finishRefresh(true);
                    }
                });
    }

    //初始化下拉刷新控件
    private void initSmartRefreshLayout() {
        smartRefreshLayout.setEnableLoadmore(false);
        smartRefreshLayout.setRefreshHeader(new CustomRefreshHeader(getActivity()));
        smartRefreshLayout.setRefreshFooter(new CustomRefreshFooter(getActivity(), "加载中…"));
        smartRefreshLayout.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        smartRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //  presenter.onLoadMore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                dataBeanList.clear();
                initData();
            }
        });

    }

    private void getData(JSONObject response) {
        dataBeanList.clear();
        JSONArray array = response.getJSONArray("data");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);     //将array中的数据进行逐条转换
            ChartDataBean.DataBean rowsBean = (ChartDataBean.DataBean) JSONObject.toJavaObject(object, ChartDataBean.DataBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            rowsBean.getBgm_id();
            dataBeanList.add(rowsBean);
        }
        if (0 == dataBeanList.size()) {
            noData.setVisibility(View.VISIBLE);
            Log.d("sddddd", "我的发布1111");
            publicDisplayListnener.onPublicDisplay("0");
            smartRefreshLayout.setEnableRefresh(false);
        } else {
            noData.setVisibility(View.GONE);
            publicDisplayListnener.onPublicDisplay("1");
            smartRefreshLayout.setEnableRefresh(true);
        }
        personalAdapter = new PersonalAdapter(getActivity(), dataBeanList);
        gridview.setAdapter(personalAdapter);
        personalAdapter.setDeleteListener(this);
        personalAdapter.notifyDataSetChanged();
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ChartDataBean.DataBean dataBean = (ChartDataBean.DataBean) adapterView.getAdapter().getItem(i);
                Hawk.put("ChartDataBean", dataBean);
                //  素材类型 0:文本类型 、1:绘本类型、2:影视类型
                if ("0".equals(dataBean.getMaterial().getType())) {
                    Intent intent = new Intent(getActivity(), AuditionActivity.class);
                    getActivity().startActivity(intent);

                } else if ("1".equals(dataBean.getMaterial().getType())) {
                    Intent intent = new Intent(getActivity(), PictureBookAuditionActivity.class);
                    getActivity().startActivity(intent);
                }
            }
        });
    }

    @Override
    protected void initView() {
        stateView.getBackground().setAlpha(153);
    }

    @Override
    public void onDeleteClick(int id) {
        //    deleteDrafts(id);
        showDialog("0", id);
    }

    @Override
    public void onDEleteAll(String flag) {
        showDialog("1", -1);
    }

    private void deleteDrafts(int id,String  flag) {

        //dataBeanList.clear();
        NetWorkManager.getInstance().getNetWorkApiService().deletePubilcData(id).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                       // dataBeanList.clear();
                        if (flag.equals("1")){


                        }else {

                            getMyPublicData();
                        }

                        Toast.makeText(getActivity(), "删除成功！", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(constant.PERSONAL_MYRECEIVER);
                        getActivity().sendBroadcast(intent);      //发送广播
                    }
                });
    }

    private void deleteAllData() {

        NetWorkManager.getInstance().getNetWorkApiService().deleteAllPubilcData().compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        dataBeanList.clear();
                        getMyPublicData();
                        Toast.makeText(getActivity(), "删除全部成功！", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(constant.PERSONAL_MYRECEIVER);
                        getActivity().sendBroadcast(intent);      //发送广播
                    }
                });
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        PersonalActivity personalActivity = (PersonalActivity) activity;
        personalActivity.setDeleteAllPubilcDataListener(this);
        publicDisplayListnener = (PublicDisplayListnener) getActivity();
    }

    private void showDialog(String flag, int id) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_delete, null);
        Button confirm = view.findViewById(R.id.confir_btn);
        Button cancel = view.findViewById(R.id.cancel_btn);
        TextView tv = view.findViewById(R.id.tips);
        if ("1".equals(flag)) {
            tv.setText("确定要全部删除吗？");
        } else {
            tv.setText("确定要删除吗？");
        }
        deleteDialog = DialogPlus.newDialog(getActivity())
                .setContentHolder(new ViewHolder(view))
                .setCancelable(true)
                .setGravity(Gravity.CENTER)
                .setOnDismissListener(new OnDismissListener() {
                    @Override
                    public void onDismiss(DialogPlus dialog) {

                    }
                }).create();
        deleteDialog.show();
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("fdfgdfgf","1".equals(flag)+"");
                if ("1".equals(flag)) {
                   // deleteAllData();
                    if (dataBeanList!=null&&dataBeanList.size()>0){
                        for (int i=0;i<dataBeanList.size();i++){

                            deleteDrafts(dataBeanList.get(i).getId(),"1");
                        }

                    }

                } else {
                    deleteDrafts(id,"0");
                }


                deleteDialog.dismiss();
            }
        });
        /*cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteDialog.dismiss();
            }
        });*/
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (myReceiver != null) {
            getActivity().unregisterReceiver(myReceiver);
        }
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            getMyPublicData();
        }
    }
}
